package cn.lovemmd.model.admin.controller;

import com.alibaba.fastjson2.JSON;
import cn.lovemmd.model.admin.common.PageResult;
import cn.lovemmd.model.admin.common.Result;
import cn.lovemmd.model.admin.service.UserService;
import cn.lovemmd.model.admin.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 用户管理控制器V2
 * 使用FastJson2进行JSON序列化
 * 
 * @author TLS
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/v2/user")
@Api(tags = "用户管理V2")
@Validated
@RequiredArgsConstructor
public class UserControllerV2 {

    private static final Logger log = LoggerFactory.getLogger(UserControllerV2.class);
    private final UserService userService;

    /**
     * 分页查询用户列表
     */
    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("分页查询用户列表")
    public ResponseEntity<String> getUserList(
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") Long page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Long size,
            @ApiParam("搜索关键字") @RequestParam(required = false) String search,
            @ApiParam("用户状态") @RequestParam(required = false) Integer status) {
        
        try {
            PageResult<UserVO> result = userService.getUserPage(page, size, search, status);
            Result<PageResult<UserVO>> response = Result.success(result);
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            Result<String> errorResponse = Result.error("查询用户列表失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }

    /**
     * 根据ID查询用户详情
     */
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("根据ID查询用户详情")
    public ResponseEntity<String> getUserById(
            @ApiParam("用户ID") @PathVariable @NotNull Long id) {
        
        try {
            UserVO user = userService.getUserById(id);
            if (user == null) {
                Result<String> errorResponse = Result.error("用户不存在");
                return ResponseEntity.ok(JSON.toJSONString(errorResponse));
            }
            Result<UserVO> response = Result.success(user);
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("查询用户详情失败", e);
            Result<String> errorResponse = Result.error("查询用户详情失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }

    /**
     * 修改用户密码
     */
    @PostMapping(value = "/password", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("修改用户密码")
    public ResponseEntity<String> updateUserPassword(
            @ApiParam("用户ID") @RequestParam @NotNull Long userId,
            @ApiParam("新密码") @RequestParam @NotNull String newPassword) {
        
        try {
            boolean success = userService.updateUserPassword(userId, newPassword);
            Result<String> response = success ? 
                Result.success("修改密码成功") : 
                Result.error("修改密码失败");
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("修改用户密码失败", e);
            Result<String> errorResponse = Result.error("修改用户密码失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }

    /**
     * 封禁用户
     */
    @PostMapping(value = "/ban", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("封禁用户")
    public ResponseEntity<String> banUser(
            @ApiParam("用户ID") @RequestParam @NotNull Long userId) {
        
        try {
            boolean success = userService.banUser(userId);
            Result<String> response = success ? 
                Result.success("封禁用户成功") : 
                Result.error("封禁用户失败");
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("封禁用户失败", e);
            Result<String> errorResponse = Result.error("封禁用户失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }

    /**
     * 解封用户
     */
    @PostMapping(value = "/unban", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("解封用户")
    public ResponseEntity<String> unbanUser(
            @ApiParam("用户ID") @RequestParam @NotNull Long userId) {
        
        try {
            boolean success = userService.unbanUser(userId);
            Result<String> response = success ? 
                Result.success("解封用户成功") : 
                Result.error("解封用户失败");
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("解封用户失败", e);
            Result<String> errorResponse = Result.error("解封用户失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("删除用户")
    public ResponseEntity<String> deleteUser(
            @ApiParam("用户ID") @PathVariable @NotNull Long id) {
        
        try {
            boolean success = userService.deleteUser(id);
            Result<String> response = success ? 
                Result.success("删除用户成功") : 
                Result.error("删除用户失败");
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("删除用户失败", e);
            Result<String> errorResponse = Result.error("删除用户失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping(value = "/batch", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("批量删除用户")
    public ResponseEntity<String> deleteBatchUsers(
            @ApiParam("用户ID列表") @RequestBody @NotNull List<Long> userIds) {
        
        try {
            boolean success = userService.deleteBatchUsers(userIds);
            Result<String> response = success ? 
                Result.success("批量删除用户成功") : 
                Result.error("批量删除用户失败");
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("批量删除用户失败", e);
            Result<String> errorResponse = Result.error("批量删除用户失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }

    /**
     * 获取用户统计信息
     */
    @GetMapping(value = "/stats", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("获取用户统计信息")
    public ResponseEntity<String> getUserStats() {
        
        try {
            Object stats = userService.getUserStats();
            Result<Object> response = Result.success(stats);
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("获取用户统计信息失败", e);
            Result<String> errorResponse = Result.error("获取用户统计信息失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(errorResponse));
        }
    }
}
